package com.example.bookkeepingelf.business.activity;

import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.example.bookkeepingelf.R;
import com.example.bookkeepingelf.base.utils.AsyncUtils;
import com.example.bookkeepingelf.base.utils.ResourceUtils;
import com.example.bookkeepingelf.business.adapter.AccountBookHomeListViewAdapter;
import com.example.bookkeepingelf.business.database.AppDatabase;
import com.example.bookkeepingelf.business.database.dao.AccountBookDao;
import com.example.bookkeepingelf.business.database.entity.AccountBook;
import com.example.bookkeepingelf.business.listener.MyOnClickListener;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import cn.hutool.core.collection.CollectionUtil;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link TitleFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class TitleFragment extends Fragment implements MyOnClickListener<AccountBook> {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private AccountBook mainAccountBook;
    private AppDatabase appDatabase;
    private AccountBookDao accountBookDao;

    private View view;
    private LinearLayout btnDailyLedger;
    private View popupView;

    private ImageView mainIconImageView;
    private TextView mainTextView;
    private ListView listView;

    private PopupWindow popupWindow;

    private List<AccountBook> items = new ArrayList<>();

    private AccountBookHomeListViewAdapter accountBookHomeListAdapter;


    private Handler handler = new Handler(Objects.requireNonNull(Looper.myLooper())) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 1:
                    // 判断是否需要设置高度
                    if (items.size() >= 7) {
                        popupWindow.setHeight(1200);
                    }
                    popupWindow.showAsDropDown(btnDailyLedger); // 在按钮下方显示
                    break;
                case 2:
                    if (accountBookHomeListAdapter != null) {
                        accountBookHomeListAdapter.clear(); // 清空现有数据
                        accountBookHomeListAdapter.addAll(items); // 添加新的数据
                        accountBookHomeListAdapter.notifyDataSetChanged();
                    }
                    break;
                case 3:
                    // 设置主账户图标
                    settingMainAccountBook();
                    break;
            }
        }
    };

    private void settingMainAccountBook() {
        if (this.mainAccountBook == null) {
            return;
        }
        int iconResourceId = ResourceUtils.getIconResourceId(view.getContext(), mainAccountBook.getIcon());
        mainIconImageView.setImageResource(iconResourceId);
        mainTextView.setText(mainAccountBook.getAccountBookName());
    }

    public TitleFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment TitleFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static TitleFragment newInstance(String param1, String param2) {
        TitleFragment fragment = new TitleFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        this.view = inflater.inflate(R.layout.fragment_title, container, false);
        popupView = inflater.inflate(R.layout.popup_layout2, null);
        this.mainIconImageView = view.findViewById(R.id.main_icon_image_view);
        this.mainTextView = view.findViewById(R.id.main_text_view);
        // 获取数据库实例
        this.appDatabase = AppDatabase.getDatabase(getContext());
        this.accountBookDao = appDatabase.accountBookDao();
        this.initLoadingMainAccountBook();
        //初始化PopupWindow
        this.popupWindow = new PopupWindow(popupView, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);

        // 加载 button_layout.xml 文件
        this.btnDailyLedger = view.findViewById(R.id.btn_daily_ledger);
        // 设置点击事件
        this.btnDailyLedger.setOnClickListener(v1 -> {
            //获取数据, 发送消息
            AsyncUtils.runSingle(() -> {
                List<AccountBook> accountBooks = this.accountBookDao.getAll();
                if (CollectionUtil.isEmpty(accountBooks)) {
                    accountBooks.sort(Comparator.comparing(AccountBook::getUpdateTime).reversed());
                    //获取数据
                    items = accountBooks;
                }
                Message message = new Message();
                message.what = 1;
                handler.sendMessage(message);

            }, true);

            this.listView = this.popupView.findViewById(R.id.list_view);
            // 创建 ArrayAdapter 并指定布局文件 android.R.layout.simple_list_item_1
            this.accountBookHomeListAdapter = new AccountBookHomeListViewAdapter(v1.getContext(), R.layout.account_book_home_list, items, this);
            this.listView.setAdapter(accountBookHomeListAdapter);

            //切换到账本添加
            LinearLayout addAccountBookView = this.popupView.findViewById(R.id.btn_daily_ledger_add_account_book);
            addAccountBookView.setOnClickListener(v2 -> {
                Intent intent = new Intent(getContext(), AddAccountBookActivity.class);
                startActivity(intent);
            });

            //切换到账本管理
            LinearLayout accountBookManageView = this.popupView.findViewById(R.id.btn_daily_ledger_edit_account_book_manage);
            accountBookManageView.setOnClickListener(v2 -> {
                Intent intent = new Intent(getContext(), AccountBookManageActivity.class);
                startActivity(intent);
            });
        });
        return view;
    }

    /**
     * 初始化加载主账本
     */
    private void initLoadingMainAccountBook() {
       AsyncUtils.runSingle(() -> {
           this.mainAccountBook = this.accountBookDao.getMainAccountBook();
           Message message = new Message();
           message.what = 3;
           handler.sendMessage(message);
       }, true);

    }

    /**
     *
     */
    public void refreshListView(){
        AsyncUtils.runSingle(() -> {
            List<AccountBook> accountBooks = this.accountBookDao.getAllOrderByUpdateTime();
            if (CollectionUtil.isEmpty(accountBooks)) {
                return;
            }
            accountBooks.sort(Comparator.comparing(AccountBook::getUpdateTime).reversed());
            this.items = accountBooks;
            Message message = new Message();
            message.what = 2;
            handler.sendMessage(message);
        }, true);
    }

    @Override
    public void onResume() {
        super.onResume();
        this.refreshListView();

        this.onResumeChangeMain();
    }

    private void onResumeChangeMain() {
        AsyncUtils.runSingle(() -> {
            AccountBook accountBook = this.accountBookDao.getMainAccountBook();
            if (Objects.nonNull(accountBook)) {
                this.changeMain(accountBook);
            }

        }, true);
    }


    @Override
    public void onMyClick(AccountBook accountBook) {
        this.switchMainAccountBook(accountBook);
    }

    private void switchMainAccountBook(AccountBook accountBook) {
        //查询主账本
        AccountBookDao accountBookDao = this.appDatabase.accountBookDao();

        AsyncUtils.runSingle(() -> {
            AccountBook oldMainAccountBook = accountBookDao.getMainAccountBook();

            accountBook.setUpdateTime(new Date());
            accountBook.setMain(true);
            // 判断是否是主账本
            if (Objects.nonNull(oldMainAccountBook) && !oldMainAccountBook.getId().equals(accountBook.getId())) {
                oldMainAccountBook.setMain(false);
                accountBookDao.update(oldMainAccountBook);
            }
            accountBookDao.update(accountBook);

            this.changeMain(accountBook);

        }, true);
    }

    /**
     * 切换主账本
     * @param accountBook
     */
    private void changeMain(AccountBook accountBook) {
        Message message = new Message();
        message.what = 3;
        this.mainAccountBook = accountBook;
        handler.sendMessage(message);
    }

}